import { useState, useEffect, useRef } from 'react'
import React from 'react';
import { Button, Form, Input, InputNumber, message, Upload } from 'antd';
import { useLocation } from 'react-router-dom'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig } from '@wangeditor/editor'
import type { FormInstance } from 'antd/es/form';
import { newAdd,newUpd } from '../../api/school'//接口
import { useNavigate } from 'react-router-dom';
import '../school/schoolAdd.scss'
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};
const SchoolAdd: React.FC = () => {
    const location = useLocation()
    const { state } = location
    const token: any = localStorage.getItem('token')    
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const formRef = React.useRef<FormInstance>(null);

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        console.log(info);

        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            let url = info.fileList[0].response.data.src
            setImageUrl(url)
        }
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const [editor, setEditor] = useState<IDomEditor | null>(null) // 存储 editor 实例
    const [content, setHtml] = useState('') // 编辑器内容

    // 模拟 ajax 请求，异步设置 html
    useEffect(() => {
        setTimeout(() => {
            setHtml(content)
        }, 1500)
    }, [])

    const toolbarConfig = {}
    const editorConfig: Partial<IEditorConfig> = {
        placeholder: '请输入内容...',
    }
    const navigate=useNavigate()
    // 添加接口
    const addNew = async (params: any) => {
        let res: any = await newAdd(params)
        // console.log(res);
        if(res.code==='00000'){
            navigate('/index/SchoolList')
        }

    }
     // 修改
     const updNew=async(id:number,params:any)=>{
        // console.log(params);
        let res:any=await newUpd(id,params)
        // console.log(res);
        if(res.code==='00000'){
            navigate('/index/SchoolList')
        }
        
    }
    //点击添加 
    const onFinish = (values: any) => {
        const params = { ...values, thumb: imageUrl, content }
       if(state){
            updNew(state.news_id,params)
       }else{
            addNew(params)
       }

    };
   
    const [form] = Form.useForm();
    // 重置
    const onReset = () => {
        // form.resetFields()
    };
    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])
    useEffect(()=>{
        formRef.current?.setFieldsValue(state)
        // console.log(state);
        if(state){
            setImageUrl(state.thumb)
        }
    },[])
    return (<div className='schooladd'>
        <h3>{state?'修改':'添加'}</h3>
        <div className="form">
            <Form
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 450 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
                form={form}
                ref={formRef}
            >
                <Form.Item name='title' label="标题" rules={[{ required: true, message: '请输入标题' }]}>
                    <Input />
                </Form.Item>
                <Form.Item name='keywords' label="关键字" rules={[{ required: true, message: '请输入关键字' }]}>
                    <Input />
                </Form.Item>
                <Form.Item name='author' label="作者" rules={[{ required: true, message: '请输入作者' }]}>
                    <Input />
                </Form.Item>
                <Form.Item name='desc' label="介绍" rules={[{ required: true, message: '请填写介绍' }]}>
                    <Input.TextArea />
                </Form.Item>
                <Form.Item name='thumb' label="缩略图" >
                    <div>
                        <Upload
                            name="file"
                            headers={{ Authorization: sessionStorage.getItem('token') as any }}
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://121.42.230.80/api/visit/upload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </div>
                </Form.Item>
                <Form.Item name='content' label="正文">
                    <div style={{ border: '1px solid #ccc', zIndex: 100, width: '900px' }}>
                        <Toolbar
                            editor={editor}
                            defaultConfig={toolbarConfig}
                            mode="default"
                            style={{ borderBottom: '1px solid #ccc' }}
                        />
                        <Editor
                            defaultConfig={editorConfig}
                            value={state?state.content:''}
                            onCreated={setEditor}
                            onChange={editor => setHtml(editor.getHtml())}
                            mode="default"
                            style={{ height: '500px', 'overflowY': 'hidden' }}
                        />
                    </div>

                </Form.Item>
                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                    <Button onClick={onReset}>重置</Button>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </Form>
        </div>
    </div>)
}
export default SchoolAdd